package com.lz.sports.ui.manager

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import com.lz.comm.BR
import com.lz.comm.image.GlideApp
import com.lz.library.base.BaseActivity
import com.lz.library.extension.APP
import com.lz.library.extension.click
import com.lz.library.extension.resString
import com.lz.library.permission.FlowPermission
import com.lz.library.utils.ActivityScrollObserver
import com.lz.sports.BuildConfig
import com.lz.sports.R
import com.lz.sports.bean.ParcelableString
import com.lz.sports.core.ProjectManager
import com.lz.sports.databinding.ActExamineeAddBinding
import com.lz.sports.dialog.ParcelableSelectDialog
import com.lz.sports.utils.UploadUtils
import com.lz.sports.utils.compressBitmapAndSave
import com.lz.sports.vm.manager.ExamineeAddViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


//考生新增
class ExamineeAddActivity : BaseActivity<ExamineeAddViewModel, ActExamineeAddBinding>(),
    ParcelableSelectDialog.OnSelectedListener {

    //拍照与图库
    private lateinit var cameraLauncher: ActivityResultLauncher<Intent>
    private lateinit var photoLauncher: ActivityResultLauncher<Intent>

    //权限申请
    private val permissions by lazy { FlowPermission(this) }

    override fun getLayoutRes(): Int = R.layout.act_examinee_add

    override fun getVMVariableId(): Int = BR.vm

    override fun initObserve() {
        photoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK && result.data != null) {
                val path = UploadUtils.tmpPhotoPath().absolutePath
                UploadUtils.copyUriFile(result.data!!.data!!, path)
                val bitmap = compressBitmapAndSave(path)
                GlideApp.with(this).load(bitmap).into(binding.ivLogo)
                viewModel.photoPath(path)
            }
        }
        cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val path = UploadUtils.tmpPhotoPath().absolutePath
                val bitmap = compressBitmapAndSave(path)
                GlideApp.with(this).load(bitmap).into(binding.ivLogo)
                viewModel.photoPath(path)
            }
        }
    }

    override fun initData(savedState: Bundle?) {
        ActivityScrollObserver.observe(this, binding.root)
        lifecycleScope.launch {
            arrayOf(binding.tvCamera, binding.tvUpload, binding.tvSave, binding.tvProject)
                .click()
                .collect { view ->
                    when (view.id) {
                        R.id.tv_camera -> startCamera()
                        R.id.tv_upload -> startPhoto()
                        R.id.tv_save -> viewModel.save()
                        R.id.tv_project -> {
                            val areaList = ProjectManager.examPlan?.examProjectList
                            if (areaList != null && areaList.isNotEmpty()) {
                                ParcelableSelectDialog.show(this@ExamineeAddActivity, R.string.select.resString(),
                                    viewModel.examProject.value, areaList as ArrayList<out ParcelableString>
                                )
                            }
                        }
                    }
                }
        }
    }

    //照相机
    private fun startCamera() {
        lifecycleScope.launch {
            permissions.request(Manifest.permission.CAMERA).collect {
                if (it) {
                    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                    if (intent.resolveActivity(packageManager) != null) {
                        val uri = FileProvider.getUriForFile(
                            APP,
                            "${BuildConfig.APPLICATION_ID}.fileProvider",
                            UploadUtils.tmpPhotoPath()
                        )
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
                        cameraLauncher.launch(intent)
                    }
                }
            }
        }
    }

    //相册
    private fun startPhoto() {
        val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/*" }
        if (intent.resolveActivity(packageManager) != null) {
            photoLauncher.launch(intent)
        }
    }

    override fun onSelected(dialog: ParcelableSelectDialog, position: Int, requestCode: Int) {
        dialog.dismiss()
        viewModel.selectProject(position)
    }
}